package com.github.aloxc.plugin.restplus.listener;

import com.github.aloxc.plugin.restplus.entity.RestConfig;
import com.github.aloxc.plugin.restplus.entity.UserCase;
import com.github.aloxc.plugin.restplus.navigator.RestServiceDetail;
import com.github.aloxc.plugin.restplus.navigator.RestServicesNavigator;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Map;

public class DeleteUserCaseListener extends MouseAdapter {
    private RestServiceDetail restServiceDetail;

    public DeleteUserCaseListener(RestServiceDetail restServiceDetail){

        this.restServiceDetail = restServiceDetail;
    }
    @Override
    public void mouseClicked(MouseEvent e) {
        super.mouseClicked(e);
        DefaultTreeModel treeModel = (DefaultTreeModel) restServiceDetail.getUserCaseTree().getModel();
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) restServiceDetail.getUserCaseTree().getLastSelectedPathComponent();// 获得选中的欲删除节点
        if (node == null) {
            return;
        }
        // 查看欲删除的节点是否为根节点，根节点不允许删除
        DefaultMutableTreeNode nextSelectedNode = node.getNextSibling();// 获得下一个兄弟节点，以备选中
        if (nextSelectedNode == null) {
            // 查看是否存在兄弟节点
            nextSelectedNode = node.getPreviousSibling();
        }
        String name = (String) node.getUserObject();
        RestConfig config = restServiceDetail.getProject().getComponent(RestServicesNavigator.class).getConfig();
        Map<String, UserCase> userCaseMap = config.getUserCaseMap().
                get((restServiceDetail.getParentName() != null ? restServiceDetail.getParentName() + ":" : "") + restServiceDetail.getUrl());
        userCaseMap.remove(UserCase.getUserCaseKey(name,restServiceDetail.getMethod()));
        config.save(restServiceDetail.getProject());
        treeModel.removeNodeFromParent(node);// 删除节点
        if (nextSelectedNode != null) {
            restServiceDetail.getUserCaseTree().setSelectionPath(new TreePath(nextSelectedNode.getPath()));// 选中节点
        } else {
            restServiceDetail.getUserCaseTree().setSelectionPath(null);// 选中节点
        }
    }
}
